<template>
	<view class="resultTask">
		<uni-nav-bar
			color="#ffffff"
			background-color="#00aded"
			:statusBar="true"
			title="计时_签吨作业"
			fixed="true"
			left-icon="left"
			left-text="返回"
			@clickLeft="back"
			@clickRight="arrow"
			right-icon="right"
			right-text="实绩"
		></uni-nav-bar>
		<view class="resultTask_top" v-if="transOrderNumber == null">
			<uni-section title="点击图形开始扫描" type="line" titleFontSize="20px">
				<uni-icons type="scan" size="80" @click="onScan"></uni-icons>
			</uni-section>
		</view>
		<dil-toast v-if="showDilToast" :title="dilToastTitle"></dil-toast>
		<view class="resultTask_main">
			<uni-section title="运单信息" type="line" title-font-size="20px">
				<template v-slot:right v-if="transOrderNumber != null">
					<view @click="cancelMask" style="font-weight: 500; font-size: 16px; color: red">
						<text>取消计时</text>
					</view>
				</template>
				<dil-search :columnData="options.columnDataList" @onSearch="onSearch" class="dilSearch" v-if="transOrderNumber == null"></dil-search>
				<dil-card class="dilCard" @emitEvent="emitEvent" v-bind.sync="options"></dil-card>
			</uni-section>
		</view>
		<view class="resultTask_middle" v-if="transOrderNumber != null">
			<uni-section title="计时信息" type="line" titleFontSize="20px">
				<uni-card margin="10rpx" padding="4rpx">
					<view class="countTime">
						<bing-countup ref="countUp" v-bind.sync="bingCountMap" :font-size="30" :auto-start="false" color="#FFFFFF" background-color="#007AFF" />
					</view>
					<view class="buttonClass">
						<button type="primary" class="button" @click="onclickConfirmDebounce(item)" v-for="(item, index) in nextStepValue" :key="index">
							{{ item.label }}
						</button>
					</view>
				</uni-card>
			</uni-section>
		</view>
		<view class="resultTask_floot" v-if="transOrderNumber != null">
			<uni-section title="运单实绩" type="line" titleFontSize="20px">
				<dil-step :stepsList="stepList"></dil-step>
			</uni-section>
		</view>
		<view class="editActualDuration">
			<uni-popup ref="editActualDuration_popup" type="bottom" border-radius="10px 10px 0 0" background-color="#fff" style="width: 100%">
				<view class="editActualDuration_main" style="width: 95vw">
					<view class="tip">
						<text style="font-weight: 700">提示</text>
						<text style="font-size: 30rpx; color: #ff0000">请确认运单以下信息</text>
					</view>
					<view class="importData" v-for="(item, index) in importData" :key="index">
						<text v-if="currentItem[item.prop] != null" style="color: #000000">{{ item.label }}</text>
						<text v-if="currentItem[item.prop] != null">{{ currentItem[item.prop] }}</text>
					</view>
					<dil-Form formId="767" ref="form" v-model="form_time" class="dilForm" labelPosition="left" labelWidth="80px"></dil-Form>
				</view>
				<view class="editActualDuration_floot" style="text-align: center">
					<button type="warn" size="mini" style="margin: 10px" @click="closePopup()">取消</button>
					<button type="primary" size="mini" style="margin: 10px" @click="editActualDurationSubmit()">提交</button>
				</view>
			</uni-popup>
		</view>
		<view class="editActualWeight">
			<uni-popup ref="editActualWeight_popup" type="bottom" border-radius="10px 10px 0 0" background-color="#fff" style="width: 100%">
				<view class="editActualWeight_main" style="margin: 10px">
					<dil-Form formId="768" ref="form" v-model="form_weight" class="dilForm" labelPosition="right" labelWidth="140px"></dil-Form>
				</view>
				<view class="editActualWeight_floot" style="text-align: center">
					<button type="warn" size="mini" style="margin: 10px" @click="closePopup()">取消</button>
					<button type="primary" size="mini" style="margin: 10px" @click="editActualWeightSubmit()">提交</button>
				</view>
			</uni-popup>
		</view>
	</view>
</template>

<script>
import { accDiv } from '@/utils/utils.js';
export default {
	data() {
		return {
			dilToastTitle: '暂无提示',
			showDilToast: false,
			stepList: [],
			addressMap: {},
			resultStartTime: null,
			formValue: {},
			form_time: {},
			form_weight: {},
			bingCountMap: {
				hour: 0,
				minute: 0,
				second: 0
			},
			options: {
				requestUrl: '/api/v1/tms/getTransOrderList?apiId=627',
				requestQuery: {},
				cardSlotList: [
					{
						label: '计时',
						icon: 'bars',
						emitEvent: 'excuteMake'
					},
					{
						label: '签时',
						icon: 'bars',
						emitEvent: 'editActualDuration'
					},
					{
						label: '计吨',
						icon: 'bars',
						emitEvent: 'editActualWeight'
					}
				],
				columnDataList: [],
				totalNum: 0,
				rowDataList: [],
				importData: []
			},
			transOrderNumber: null,
			transOrderId: null,
			totalDuration: 0,
			importData: [],
			currentItem: {}
		};
	},
	onShow() {
		uni.$emit('onShow', 1);
		//获取定位
		this.Tool.getAddress({ loading: false }, (data) => {
			this.addressMap = data;
			this.formValue.loadActualAddress = this.addressMap.address;
			this.formValue = { ...this.addressMap, ...this.formValue };
		});
		// 以点进来的时间作为开始时间;
		this.resultStartTime = new Date();
	},
	watch: {
		transOrderNumber(val) {
			if (val) {
				this.getTransResult();
			}
		},
		nextStepValue: {
			handler(val) {
				this.countUp(this.stepStatus);
			},
			deep: true,
			immediate: false
		}
	},
	computed: {
		stepStatus() {
			if (this.stepList.length > 0) {
				return this.stepList[this.stepList.length - 1].TIME_TYPE;
			} else {
				return null;
			}
		},
		nextStepValue() {
			let itemStatus = this.stepStatus;
			if (itemStatus == '计时开始') {
				return [
					{
						label: '暂停开始',
						value: 3
					},
					{
						label: '计时结束',
						value: 2
					}
				];
			} else if (itemStatus == '暂停开始') {
				return [
					{
						label: '暂停结束',
						value: 4
					}
				];
			} else if (itemStatus == '暂停结束') {
				return [
					{
						label: '暂停开始',
						value: 3
					},
					{
						label: '计时结束',
						value: 2
					}
				];
			} else if (itemStatus == '计时结束') {
				return [];
			} else {
				return [
					{
						label: '计时开始',
						value: 1
					}
				];
			}
		}
	},
	beforeDestory() {
		this.transOrderNumber = null;
		this.transOrderId = null;
	},
	mounted() {
		this.getOrderSectionDebounce = this.Tool.debounce((data) => {
			this.getOrderSection(data);
		}, 150);
		this.onclickConfirmDebounce = this.Tool.debounce((data) => {
			this.onclickConfirm(data);
		}, 200);
		this.getOrderSectionDebounce({});
	},
	methods: {
		changeDilToast(title, duration) {
			let timer = null;
			this.dilToastTitle = title;
			this.showDilToast = true;
			let that = this;
			timer = setTimeout(() => {
				that.showDilToast = false;
				that.dilToastTitle = '暂无提示';
				clearTimeout(timer);
			}, duration);
		},
		excuteMake(item) {
			if (this.transOrderNumber == null) {
				this.transOrderId = item.transOrderId;
				this.transOrderNumber = item.transOrderNumber;
				this.getOrderSectionDebounce({
					transOrderId: item.transOrderId,
					transOrderNumber: item.transOrderNumber
				});
			} else {
				uni.showToast({
					duration: 2000,
					title: '无效点击',
					icon: 'none'
				});
			}
		},
		closePopup() {
			this.$refs.editActualDuration_popup.close();
			this.$refs.editActualWeight_popup.close();
		},
		//签时
		editActualDuration(item) {
			this.form_time = JSON.parse(JSON.stringify(item));
			this.importData = item.importData;
			this.currentItem = item;
			this.$refs.editActualDuration_popup.open('center');
		},
		async editActualDurationSubmit() {
			if (this.form_time.scFlag != '计时') {
				this.form_time.scFlag = '签时';
			}
			this.form_time.timeType = 2;
			this.timeTask(this.form_time, {});
			this.$refs.editActualDuration_popup.close();
		},
		//计吨
		editActualWeight(item) {
			this.importData = item.importData;
			this.currentItem = item;
			this.form_weight = JSON.parse(JSON.stringify(item));
			this.$refs.editActualWeight_popup.open('center');
		},
		async editActualWeightSubmit() {
			this.form_weight.scFlag = 1;
			const res = await this.$myRequest({
				url: '/api/v1/tms/updateTransOrder',
				data: this.form_weight
			}).catch((err) => {
				uni.showToast({
					duration: 2000,
					title: err,
					icon: 'error'
				});
			});
			if (res.data.status == 'succeed') {
				uni.showToast({
					title: res.data.message,
					duration: 2000,
					icon: 'success'
				});
				this.getOrderSectionDebounce({});
				this.getTransResult();
			} else {
				uni.showToast({
					title: res.data.message,
					duration: 2000,
					icon: 'error'
				});
			}
			this.$refs.editActualWeight_popup.close();
		},
		cancelMask() {
			this.transOrderId = null;
			this.transOrderNumber = null;
			this.getOrderSectionDebounce();
		},
		arrow() {
			uni.navigateTo({
				url: '/pages/transExecute/timeResult'
			});
		},
		onSearch(item) {
			this.getOrderSectionDebounce(item);
		},
		back() {
			uni.switchTab({
				url: '/pages/index/index'
			});
		},
		async getOrderSection(data = {}) {
			data.billingType = '计时';
			data.deleted = 5;
			data.workFlag = '计时';
			data.transOrderNumber = this.transOrderNumber;
			this.options.requestQuery = { ...data };
		},
		async getTransResult() {
			let transOrderNumber = this.transOrderNumber;
			const res = await this.$myRequest({
				url: '/api/v1/tms/getTransResult',
				data: { transOrderNumber: transOrderNumber }
			}).catch(() => {
				this.stepList = [];
			});
			if (res.data.data.length > 0) {
				this.stepList = res.data.data;
				this.computedTimeData();
			} else {
				this.stepList = [];
			}
		},
		emitEvent(eventName, cardItem) {
			this[eventName](cardItem);
		},
		//扫描事件
		onScan() {
			let that = this;
			that.$commonScan(async (data) => {
				let scanResult = data.scanResult;
				if (!scanResult.includes('YSDD') && scanResult.length != '20') {
					uni.showToast({
						title: '识别信息不符合规则,请重试',
						icon: 'none',
						duration: 2000
					});
				} else {
					that.transOrderNumber = scanResult;
					that.getOrderSection({
						workFlag: '计时',
						transOrderNumber: that.transOrderNumber
					});
				}
			});
		},
		//计时器开始事件
		countUp(status) {
			if (['计时开始', '暂停结束'].includes(status)) {
				setTimeout(() => {
					this.$refs.countUp.start();
				}, 1100);
			} else if (['暂停开始', '计时结束'].includes(status)) {
				// this.$nextTick(() => {
				// });
				setTimeout(() => {
					this.$refs.countUp.pause();
				}, 1100);
			} else {
				setTimeout(() => {
					this.$refs.countUp.reset();
				}, 1100);
			}
		},
		//计算计时时长
		computedTimeData() {
			//从计时开始、暂停开始、暂停结束、计时结束，如果没有结束，则从当前时间开始算
			let arrStep = [];
			if (this.stepList[this.stepList.length - 1].type == '计时计时结束') {
				arrStep = [...this.stepList];
			} else {
				arrStep = [
					...this.stepList,
					{
						TIME_TYPE: '当前',
						resultTime: new Date()
					}
				];
			}
			let arrStepMap = arrStep.reduce((prev, item) => {
				if (item.TIME_TYPE && Object.keys(prev).length == 0) {
					return item;
				}
				if (item.TIME_TYPE && ['计时开始', '暂停结束'].includes(prev.TIME_TYPE) && ['计时结束', '暂停开始', '当前'].includes(item.TIME_TYPE)) {
					item.totalDuration = new Date(item.resultTime).getTime() - new Date(prev.resultTime).getTime() + (prev.totalDuration ? prev.totalDuration : 0);
					return item;
				}
				item.totalDuration = prev.totalDuration;
				return item;
			}, {});
			let hour = parseInt(arrStepMap.totalDuration / (1000 * 60 * 60));
			let minute = parseInt((arrStepMap.totalDuration - 60 * 60 * 1000 * hour) / (1000 * 60));
			let second = parseInt((arrStepMap.totalDuration - 60 * 60 * 1000 * hour - 1000 * 60 * minute) / 1000);
			this.totalDuration = arrStepMap.totalDuration ? arrStepMap.totalDuration : 0;
			this.bingCountMap = { hour, minute, second };
		},
		//确认事件
		onclickConfirm(item) {
			let that = this;
			that.computedTimeData();
			let timeHour = accDiv(that.totalDuration, 3600000).toFixed(1);
			//获取小数位置
			let floorTimeHour = Math.floor(timeHour);
			if (timeHour - floorTimeHour >= 0.1) {
				timeHour = floorTimeHour + 0.5;
			} else if (timeHour - floorTimeHour > 0.5) {
				timeHour = floorTimeHour + 1;
			} else {
				timeHour = floorTimeHour;
			}
			if (item.value == 2) {
				this.importData = this.options.importData;
				this.currentItem = this.options.rowDataList[0];
				that.form_time = {
					timeDuration: timeHour,
					actualDuration: timeHour,
					transOrderId: this.options.rowDataList[0].transOrderId,
					standardDuration: this.options.rowDataList[0].actualDuration,
					transOrderNumber: this.transOrderNumber,
					scFlag: '计时'
				};
				that.$refs.editActualDuration_popup.open('center');
			} else {
				uni.showModal({
					cancelText: '取消',
					confirmText: '确认',
					title: '提示	',
					content: `确认是否${item.label}`,
					editable: false,
					success: (res) => {
						console.log(res, 'res');
						if (res.confirm) {
							let map = {
								timeType: item.value,
								transOrderId: this.options.rowDataList[0].transOrderId,
								actualDuration: res.content
							};
							that.timeTask(map, item);
						} else if (res.cancel) {
							uni.showToast({
								title: '用户取消操作！',
								icon: 'none',
								duration: 3000
							});
						}
					}
				});
			}
		},
		//调用计时接口
		async timeTask(map, item) {
			const res = await this.$myRequest({
				url: '/api/v1/tms/startend',
				data: map
			}).catch((err) => {
				// uni.showToast({
				// 	duration: 5000,
				// 	title: err,
				// 	icon: 'none'
				// });
				this.changeDilToast(err, 5000);
			});
			if (res.data.status == 'succeed') {
				uni.showToast({
					title: res.data.message,
					duration: 3000,
					icon: 'success'
				});
				this.getOrderSectionDebounce({
					transOrderNumber: this.transOrderNumber
				});
				this.getTransResult();
				this.form_time = {};
			} else {
				// uni.showToast({
				// 	title: res.data.message,
				// 	icon: 'none',
				// 	duration: 5000
				// });
				this.changeDilToast(res.data.message, 5000);
			}
		}
		//vuex
	}
};
</script>

<style lang="scss" scoped>
.resultTask {
	width: 100vw;
	height: 100%;
	background-color: #f5f5f5;
	display: flex;
	justify-content: center;
	align-items: center;
	flex-direction: column;
	&_top {
		width: 100vw;
		height: 100%;
		.uni-section {
			width: 100vw;
			/deep/.uni-section-content {
				display: flex;
				justify-content: center;
				align-items: center;
				flex-direction: column;
			}
		}
	}
	.resultTask_top_result {
		margin-top: 10rpx;
		.scroll-Y {
			height: 90vh;
		}
	}
	&_main {
		margin-top: 10rpx;
		width: 100vw;
		height: 100%;
		.uni-section {
			width: 100vw;
			.dilSearch {
				width: 100%;
			}
			/deep/.uni-section-content {
				display: flex;
				justify-content: center;
				align-items: center;
				flex-direction: column;
			}
		}
	}
	&_middle {
		margin-top: 10rpx;
		.uni-section {
			width: 100vw;
			/deep/.uni-section-content {
				display: flex;
				justify-content: center;
				align-items: center;
			}
			/deep/.uni-card {
				border-radius: 40rpx;
				.buttonClass {
					margin-top: 20rpx;
					display: flex;
					justify-content: center;
					align-items: center;
				}
				.button {
					border-radius: 40rpx;
				}
			}
		}
	}
	&_floot {
		width: 100vw;
		background-color: #fff;
		margin-top: 20rpx;
		margin-bottom: 20rpx;
		border-radius: 20rpx;
	}
	.editActualDuration {
		&_main {
			.tip {
				font-size: 32rpx;
				font-weight: 500;
				display: flex;
				flex-direction: column;
				justify-content: center;
				align-items: center;
				text {
					margin-top: 20rpx;
				}
			}
			.importData {
				margin-top: 20rpx;
				font-size: 32rpx;
				font-weight: 700;
				color: #ff0000;
				text {
					padding: 20rpx;
				}
			}
			.dilForm {
				width: 90%;
				margin-left: 20rpx;
				/deep/.uni-forms .uni-forms-item .uni-forms-item__label {
					font-weight: 700;
					color: #000;
					font-size: 32rpx;
				}
				/deep/.uni-forms .uni-forms-item .uni-forms-item__content {
					font-weight: 700;
					color: #000;
					font-size: 32rpx;
				}

				/deep/.uni-forms .uni-forms-item .uni-forms-item__content .uni-input-placeholder {
					font-weight: 700;
					// color: #ff0000;
					font-size: 28rpx;
				}
				/deep/.uni-forms .uni-forms-item .uni-forms-item__content .uni-input-input:disabled {
					font-weight: 700;
					color: #ff0000;
					font-size: 28rpx;
				}
				// display: flex;
				// justify-content: center;
				// align-items: center;
			}
		}
	}
	.editActualWeight {
		&_main {
			.tip {
				font-size: 32rpx;
				font-weight: 500;
				display: flex;
				flex-direction: column;
				justify-content: center;
				align-items: center;
				text {
					margin-top: 20rpx;
				}
			}
			.importData {
				margin-top: 20rpx;
				font-size: 32rpx;
				font-weight: 700;
				color: #ff0000;
				text {
					padding: 20rpx;
				}
			}
			.dilForm {
				width: 90%;
				margin-left: 20rpx;
				/deep/.uni-forms .uni-forms-item .uni-forms-item__label {
					font-weight: 700;
					color: #000;
					font-size: 32rpx;
				}
				/deep/.uni-forms .uni-forms-item .uni-forms-item__content {
					font-weight: 700;
					color: #000;
					font-size: 32rpx;
				}

				/deep/.uni-forms .uni-forms-item .uni-forms-item__content .uni-input-placeholder {
					font-weight: 700;
					// color: #ff0000;
					font-size: 28rpx;
				}
				/deep/.uni-forms .uni-forms-item .uni-forms-item__content .uni-input-input:disabled {
					font-weight: 700;
					color: #ff0000;
					font-size: 28rpx;
				}
				// display: flex;
				// justify-content: center;
				// align-items: center;
			}
		}
	}
}
</style>
